<?php

namespace App\Http\Controllers\Manage;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\Notification;
use App\Models\SystemUser;
use App\Notifications\InvoicePaid;
use Illuminate\Http\Request;
//公告管理
class AnnouncementController extends Controller
{
    use ResponseData;
    public function list(Announcement $model,Request $request){
        $data = $model
            ->append('unread')
            ->orderBy('id','desc')->get();

        return $this->success($data);
    }
    public function store(Announcement $model,Request $request,SystemUser $user){
        $data = $request->all();
        $model->fill($data);
        $model->save();
        $u = $user->query()->where('id','>',0)->get();
        foreach ($u as $v){
            $v->isDb=1;//数据库发送
            $v->notify(new InvoicePaid($model));
        }

        return $this->success($model);
    }
    public function edit(Announcement $model,Request $request){
        $data = $model->find($request->id);
        return $this->success($data);
    }
    public function update(Announcement $model,Request $request){
        $data = $model->find($request->id);
        $data->update($request->all());
        return $this->success('修改成功');
    }
    public function destory(Announcement $model,Request $request){
        $data = $model->find($request->id);
        $data->delete();
    }
    //获取未读列表
    public function getOrderList(Notification $notification,Request $request){
        if($request->filled('id')){
            $notification = $notification->where('data',$request->id);
        }
        $data = $notification->with(['user'=>function($query){
            $query->with('first','two','three');
        }])
            ->orderBy('data')
            ->whereNull('read_at')
            ->get();
        return $this->success($data);
    }
    //设置未读变成已读消息
    public function setRead(Notification $model,Request $request){
        $user = $request->user();
        $model->where('notifiable_id',$user->id)
            ->where('data',$request->id)
            ->update(['read_at'=>now()]);
        return $this->success('更新成功');
    }
}
